package demo;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class SimpleFileClient {

    public static String upload(String path) {
        final String newLine = "\r\n";
        final String boundaryPrefix = "--";
        String BOUNDARY = "--------------------------103931284980883249653797";
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://127.0.0.1:8090/file/upload").openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());

            // 上传文件
            File file = new File(path);
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行，然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);

            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();

            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();
            if (httpURLConnection.getResponseCode() != 200) {
                return "上传失败";
            }
            return "上传成功";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    public static String download(String uuid) {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://127.0.0.1:8090/file/download?uuid=" + uuid).openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() != 200) {
                return "下载失败";
            }
            InputStream is = httpURLConnection.getInputStream();
            byte[] b = new byte[1024];
            int j;

            String content = httpURLConnection.getHeaderField("Content-Disposition");
            String fileName = content.substring(content.lastIndexOf("=")+1);
            File fileDir = new File("D:\\filetest\\download");
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream("D:\\filetest\\download\\"+fileName);
            while ((j = is.read(b)) != -1) {
                fos.write(b, 0, j);
                fos.flush();
            }
            is.close();
            fos.close();
            return "下载成功";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    public static String getFileInfo(String uuid) {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://127.0.0.1:8090/file/info?uuid=" + uuid).openConnection();
            httpURLConnection.setRequestMethod("GET");
            InputStream is = httpURLConnection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            String jsonString = byteArrayOutputStream.toString();
            byteArrayOutputStream.close();
            is.close();
            return jsonString;
        } catch (Exception e) {
            return "获取失败";
        }

    }
}
